package com.hjx.face.javacv.face;


import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef.HMODULE;
import com.sun.jna.platform.win32.WinDef.LPARAM;
import com.sun.jna.platform.win32.WinDef.LRESULT;
import com.sun.jna.platform.win32.WinDef.WPARAM;
import com.sun.jna.platform.win32.WinUser.HHOOK;
import com.sun.jna.platform.win32.WinUser.KBDLLHOOKSTRUCT;
import com.sun.jna.platform.win32.WinUser.LowLevelKeyboardProc;
import com.sun.jna.platform.win32.WinUser.MSG;



public class KeyboardHook implements Runnable{

	private static HHOOK hhk;
	private static LowLevelKeyboardProc keyboardHook;
	final static User32 lib = User32.INSTANCE;
	private boolean [] on_off=null;

	public KeyboardHook(boolean [] on_off){
		this.on_off = on_off;
	}

	public interface KeyboardHookIntercept{
		boolean check(int keyType,int vkCode);
	}
	
	private KeyboardHookIntercept intercept=null;
	
	private boolean needIntercept=false;
	public void run() {

		HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
		//键盘Hook回调，返回1啊拦截
		keyboardHook = new LowLevelKeyboardProc() {
			public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) {
				System.out.println(wParam+"=="+info.vkCode);
				if (intercept!=null) {
					needIntercept=intercept.check(wParam.intValue(),info.vkCode);
				}
				if (needIntercept) {
					info.vkCode=0;
					return new LRESULT(1);
				}
				
				return lib.CallNextHookEx(hhk, nCode, wParam, new LPARAM(Pointer.nativeValue(info.getPointer())));
			}
		};
		hhk = lib.SetWindowsHookEx(User32.WH_KEYBOARD_LL, keyboardHook, hMod, 0);
		int result;
		MSG msg = new MSG();
		while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
			if (result == -1) {
				System.err.println("error in get message");
				break;
			} else {
				System.err.println("got message");
				lib.TranslateMessage(msg);
				lib.DispatchMessage(msg);
			}
		}
		lib.UnhookWindowsHookEx(hhk);
	}


	public KeyboardHookIntercept getIntercept() {
		return intercept;
	}


	public void setIntercept(KeyboardHookIntercept intercept) {
		this.intercept = intercept;
	}

}
